package com.cs.study.homework._0308;

import java.io.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Demo3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        //创建FutureTask对象
        FutureTask<String> futureTask = new FutureTask<>(new CopyFile(
                new File("E:\\a\\a.txt"),
                new File("E:\\a\\b.txt")));
        FutureTask<String> futureTask2 = new FutureTask<>(new CopyFile(
                new File("E:\\a\\a.txt"),
                new File("E:\\a\\c.txt")));
        FutureTask<String> futureTask3 = new FutureTask<>(new CopyFile(
                new File("E:\\a\\a.txt"),
                new File("E:\\a\\d.txt")));
        //创建线程对象
        Thread thread = new Thread(futureTask);
        Thread thread2 = new Thread(futureTask2);
        Thread thread3 = new Thread(futureTask3);
        //start
        thread.start();
        thread2.start();
        thread3.start();
        //get()获取结果
        byte[] l = futureTask.get().getBytes();
        byte[] l2 = futureTask2.get().getBytes();
        byte[] l3 = futureTask3.get().getBytes();


        FileOutputStream out = new FileOutputStream("E:\\a\\time.txt");
        out.write(l);
        out.write(l2);
        out.write(l3);


    }
}

class CopyFile implements Callable<String> {
    File oldFile;
    File newFile;

    public CopyFile(File oldFile, File newFile) {
        this.oldFile = oldFile;
        this.newFile = newFile;
    }

    @Override
    public String call() throws Exception {

        //获取开始复制时间
        long start = System.currentTimeMillis();
        try (FileInputStream in = new FileInputStream(oldFile);
             FileOutputStream out = new FileOutputStream(newFile);) {


            int readCount;
            byte[] bytes = new byte[100];


            while ((readCount = in.read(bytes)) != -1) {
                out.write(bytes);
            }
        } catch (IOException e) {
            try {
                throw new IOException();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

        }
        //获取结束赋值时间
        long end = System.currentTimeMillis();
        String s = Thread.currentThread().getName() + "复制文件花费了" + (end - start) + "ms";
        System.out.println(Thread.currentThread().getName() + "复制文件花费了" + (end - start) + "ms");
        return s;
    }
}




